import { createSlice } from '@reduxjs/toolkit'
import { http } from '@/utils/http'
import { getToken, setToken, clearToken } from '../../utils/token'

const userStore = createSlice({
  name: 'userStore',
  initialState: {
    token: getToken() || '',
    userInfo: {}
  },
  reducers: {
    setStoreToken(state, action) {
      state.token = action.payload
      setToken(action.payload)
    },
    setUserInfo(state, action) {
      state.userInfo = action.payload
    },
    removeToken(state) {
      state.token = ''
      state.userInfo = {}
      clearToken()
    }
  }
})
const { setStoreToken, setUserInfo, removeToken } = userStore.actions

// 登录,获取token
const loginAction = (loginForm) => {
  return async (dispatch) => {
    const res = await http.post('/authorizations', loginForm)
    dispatch(setStoreToken(res.data.token))
  }
}
// 获取用户信息
const getUserInfo = () => {
  return async (dispatch) => {
    const res = await http.get('/user/profile')
    dispatch(setUserInfo(res.data))
  }
}
const userReducer = userStore.reducer
export default userReducer
export {
  loginAction,
  getUserInfo,
  removeToken
}